﻿using System.Collections.Generic;
using UnityEditor.iOS.Xcode;
using System.IO;

//Info.Plist修改设置
public static class InfoPlistProcessor
{
    #region InfoPlist操作
    private static string GetInfoPlistPath(string buildPath)
    {
        return Path.Combine(buildPath, XCodeProjectConfig.INFO_PLIST_NAME);
    }
    private static PlistDocument GetInfoPlist(string buildPath)
    {
        string plistPath = GetInfoPlistPath(buildPath);
        PlistDocument plist = new PlistDocument();
        plist.ReadFromFile(plistPath);
        return plist;
    }
    private static void SetStringElementValue(PlistDocument plist, string key, string value)
    {
        PlistElement strValue = null;
        if (plist.root.values.ContainsKey(key))
        {
            var strElement = plist.root[key] as PlistElementString;
            strElement.value = value;
        }
        else
        {
            strValue = new PlistElementString(value);
            plist.root.values.Add(key, strValue);
        }
    }
    private static void ReplaceElement(string key,PlistElement configElement, PlistDocument plist)
    {
        if (plist.root.values.ContainsKey(key))
        {
            plist.root.values[key] = configElement;
        }
        else
        {
            plist.root.values.Add(key, configElement);
        }
    }
    #endregion
    /// <summary>
    /// 合并InfoPlist
    /// </summary>
    public static void MergeInfoPlist(PlistDocument projectPlist, PlistDocument configPlist)
    {
        //config中的直接从第一层替换
        var elements = configPlist.root.values;
        foreach (var item in elements)
        {
            ReplaceElement(item.Key, item.Value, projectPlist);
        }
    }
    public static void SetInfoPlist(string buildPath, XCodeProjectConfig setting)
    {
        PlistDocument projectPlist = GetInfoPlist(buildPath);
        PlistDocument configPlist = GetInfoPlist(setting.InfoPlistConfigPath);
        MergeInfoPlist(projectPlist, configPlist);
        projectPlist.WriteToFile(GetInfoPlistPath(buildPath));
    }
}